package com.ruiboyun.liveapp.http;

import android.os.Handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruiboyun.liveapp.base.App;
import com.ruiboyun.liveapp.base.Url;
import com.ruiboyun.liveapp.bean.BaseBean;
import com.ruiboyun.liveapp.bean.ChannelEntity;
import com.ruiboyun.liveapp.bean.ReviewEntity;
import com.ruiboyun.liveapp.util.sys.NetworkUtil;
import com.ruiboyun.liveapp.util.tool.Loger;
import com.ruiboyun.liveapp.util.tool.ToasUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by wushiqian on 2017/9/10.
 */

public class OkHttpManager {
    MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
    private static OkHttpClient okHttpClient;
    private static OkHttpManager instance;
    private Handler handler = new Handler();

    private OkHttpManager() {
    }

    public static OkHttpManager getInstance() {
        if (instance == null) {
            synchronized (OkHttpManager.class) {
                if (instance == null) {
                    instance = new OkHttpManager();
                    okHttpClient = new OkHttpClient();

                }
            }
        }
        return instance;
    }

    public void get(final String url, final Class cls, final OnResponseListener onResponseListener) {
        if (!NetworkUtil.isNetAvailable(App.getInstance())) {
            ToasUtil.showCenterToast("网络不可用,请检查网络");

            return;
        }
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Loger.e(url+"onFailure "+e.toString());
                        if (onResponseListener!=null){
                            onResponseListener.onException(e.toString());
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                String string = null;
                try {
                    string = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                final String finalString = string;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        int code = response.code();

                        Loger.e(url+" "+code+" onResponse "+ finalString);
                        if (code == 200) {


                                Object object = JSON.parseObject(finalString, cls);
                                onResponseListener.Success(object);

                        } else {
                            onResponseListener.onFailed(code);
                        }

                    }
                });

            }
        });
    }

    public void getChannels(String client_id, final OnResponseListener onResponseListener) {
        Map<String, String> map = new HashMap<>();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("request","channels");
        jsonObject.put("client_id",client_id);
        map.put("request", "channels");
        map.put("client_id", client_id);
        post(Url.BASE_URL, ChannelEntity.class, jsonObject, onResponseListener);
    }

    public void getReviews(String client_id, String channel_id, OnResponseListener onResponseListener) {
        Map<String, String> map = new HashMap<>();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("request","reviews");
        jsonObject.put("client_id",client_id);
        jsonObject.put("channel_id",channel_id);
        map.put("request", "reviews");
        map.put("client_id", client_id);
        map.put("channel_id", channel_id);
        post(Url.BASE_URL, ReviewEntity.class, jsonObject, onResponseListener);
    }

    public void post(final String url, final Class cls, JSONObject params, final OnResponseListener onResponseListener) {
        /*Iterator<String> iterator = params.keySet().iterator();
        FormBody.Builder builder = new FormBody.Builder();

        while (iterator.hasNext()) {
            String next = iterator.next();
            builder.add(next, params.get(next));
        }*/
        RequestBody requestBody = RequestBody.create(JSON_TYPE,params.toJSONString());

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Loger.e(url+"onFailure "+e.toString());
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) throws IOException {
                 String string = null;
                try {
                    string = response.body().string();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                final String finalString = string;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                int code = response.code();

                                Loger.e(url+" "+code+"code"+ finalString);
                                if (code == 200) {


                                        Object object = JSON.parseObject(finalString, cls);
                                        BaseBean baseBean= (BaseBean) object;

                                        onResponseListener.Success(object);

                                } else {
                                    onResponseListener.onFailed(code);
                                }

                            }
                        });

                    }
                });
            }
        });
    }
}
